package com.chj.producer_balance.mandatory;

import cn.enjoyedu.producer_balance.mandatory.ProducerMandatory;
import com.chj.producer_balance.producerconfirm.ProducerConfirmAsync;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者——失败确认模式(消费者只绑定了 hankin02)
 */
public class ConsumerProducerMandatory {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接连接到RabbitMQ
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("10.200.169.5");
        factory.setVirtualHost("chj_vhost");
        factory.setUsername("chj");
        factory.setPassword("123456");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // mandatory_test
        channel.exchangeDeclare(ProducerMandatory.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        // amq.gen-2lduZF8pVolfAsN3Hj39lw -- channel error; protocol method: #method<channel.close>(reply-code=403, reply-text=ACCESS_REFUSED
//        String queueName = channel.queueDeclare().getQueue();
        String queueName = "mandatory_test_queue";
        System.out.println("queueName == "+queueName);
        channel.queueDeclare(queueName,false,false,false,null);
        //只关注 hankin02
        String routekey="hankin02";
        channel.queueBind(queueName, ProducerMandatory.EXCHANGE_NAME, routekey);
        System.out.println(" [*] Waiting for messages......");
        // 创建队列消费者
        final Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                //记录日志到文件：
                System.out.println( "Received ["+ envelope.getRoutingKey()+ "] "+message);
            }
        };
        channel.basicConsume(queueName, true, consumer);
    }
}
